package service

import (
	"gitee.com/gopher2011/godemo/logger"
	"gitee.com/gopher2011/godemo/server/dao"
	"github.com/fatih/set"
)

// 全局公开对象
var Advertisement = advertisementService{}

// 广告表
// 私有对象，所有的方法都绑定到这个结构体上。
type advertisementService struct{}

func (p *advertisementService) Create(arg dao.Advertisement) (int64, error) {
	return 0, nil
}

func (p *advertisementService) Delete() (int64, error) {
	return 0, nil
}

func (p *advertisementService) Update(arg dao.Advertisement) (int64, error) {
	return 0, nil
}

func (p *advertisementService) FindAll(path string)map[string]*dao.Advertisement {
	pageAds, err := dao.AdvertisementDao.FindAll(path)
	if err != nil {
		logger.Errorf("advertisementService FindAll PageAd error:",err)
		return nil
	}

	adIdSet := set.New(set.NonThreadSafe) //新建一个集合

	for _,pageAd := range pageAds {
		adIdSet.Add(pageAd.AdId) //将每一个pageAd对象的 AdId放入集合中
	}

	if adIdSet.IsEmpty(){
		return nil
	}

	adMap := make(map[int]*dao.Advertisement)
	ads, err := dao.AdvertisementDao.Find(set.IntSlice(adIdSet))
	if err != nil {
		logger.Errorf("advertisementService FindAll Advertisement error:",err)
		return nil
	}
	for _,item := range ads {
		adMap[item.Id] = &item
	}

	posAdsMap := make(map[string]*dao.Advertisement,len(pageAds))

	for _,pageAd := range pageAds {
		if adMap[pageAd.AdId].IsOnline {
			posAdsMap[pageAd.Position] = adMap[pageAd.AdId]
		}
	}
	return posAdsMap
}
